package com.atguigu.flink0624.chapter11;

import com.atguigu.flink0624.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

// 静态导入

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/19 10:26
 */
public class Flink01_Table_BaseUse_2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_2", 6000L, 60));
        
        // 1. 创建表环境
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        // 2. 把流转成动态表
        Table table = tenv.fromDataStream(waterSensorStream);
        
        // select  id, sum(vc) as vc_sum from a group by id
        /*Table result = table
            .groupBy($("id"))
            .aggregate($("vc").sum().as("vc_sum"))
            .select($("id"), $("vc_sum"));*/
    
    
        Table result = table
            .groupBy($("id"))
            .select($("id"), $("vc").sum().as("sum_vc"));
        
        
        /*DataStream<Tuple2<Boolean, Row>> stream = tenv.toRetractStream(result, Row.class);
        stream.print();*/
    
        tenv
            .toRetractStream(result, Row.class)
            .filter(t -> t.f0)
            .map(t -> t.f1)
            .print();
    
        env.execute();
        
    }
}
